// 封装购物车模块

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import {
  insertCartAPI,
  findNewCartListAPI,
  delCartAPI,
  prodCountAPI,
  checkItemsAPI,
  checkAllItemsAPI,
} from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    // 1. 定义state - cartList
    const cartList = ref([]);
    const allCount = ref(0);
    // 获取最新购物车列表action
    const updateNewList = async () => {
      const res = await findNewCartListAPI();
      cartList.value = res.data.shopCarts.reduce((a, b) => {
        // 把嵌套在店铺里的购物车列表提出来
        return a.shopCartItem
          ? a.shopCartItem.concat(b.shopCartItem)
          : b.shopCartItem;
      }, []);
      getAllCount();
    };
    // 2. 定义action - addCart
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      if (isLogin.value) {
        // 登录之后的加入购车逻辑
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        // 添加购物车操作
        // 已添加过 - count + 1
        // 没有添加过 - 直接push
        // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
        const item = cartList.value.find((item) => goods.skuId === item.skuId);
        if (item) {
          // 找到了
          item.count++;
        } else {
          // 没找到
          cartList.value.push(goods);
        }
      }
    };
    // 购物车商品总数
    const getAllCount = async () => {
      const res = await prodCountAPI();
      allCount.value = res.data || 0;
    };

    // 修改购物车数量
    const changeCount = async (item, count) => {
      const params = {
        skuId: item.skuId,
        spuId: item.spuId,
        shopCartItemId: item.shopCartItemId,
        count,
      };
      await insertCartAPI(params);
      // updateNewList();
      // getAllCount();
    };

    // 删除购物车
    const delCart = async () => {
      const arr = cartList.value
        .filter((item) => item.isChecked)
        .map((item) => item.cartItemId);
      // 调用接口实现接口购物车中的删除功能
      if (arr.length >> 0) {
        await delCartAPI(arr);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        updateNewList();
        getAllCount();
      } else {
        ElMessage({
          type: "warning",
          message: "请先选中商品再删除",
        });
      }
    };

    // 清除购物车
    const clearCart = () => {
      cartList.value = [];
      allCount.value = 0;
    };
    // 单选功能
    const singleCheck = async (item, isChecked) => {
      const params = [
        {
          isChecked,
          shopCartItemId: item.cartItemId,
        },
      ];
      const res = await checkItemsAPI(params);
      item.isChecked = isChecked;
    };

    // 全选功能
    const allCheck = async (isChecked) => {
      isChecked = isChecked ? 1 : 0;
      await checkAllItemsAPI({ isChecked });
      cartList.value.map((v1, i1) => {
        v1.isChecked = isChecked;
      });
    };

    // 计算属性
    // 1. 总价 所有项的count*price之和
    const allPrice = computed(() =>
      cartList.value.reduce((a, c) => a + c.count * c.price, 0)
    );

    // 2. 已选择数量
    const selectedCount = computed(() =>
      cartList.value
        .filter((item) => item.isChecked)
        .reduce((a, c) => a + c.count, 0)
    );
    // 3. 已选择商品价钱合计
    const selectedPrice = computed(() =>
      cartList.value
        .filter((item) => item.isChecked)
        .reduce((a, c) => a + c.count * c.skuPriceFee, 0)
    );

    // 是否全选
    const isAll = computed(() =>
      cartList.value.every((item) => item.isChecked)
    );

    return {
      cartList,
      allCount,
      allPrice,
      isAll,
      selectedCount,
      selectedPrice,
      getAllCount,
      changeCount,
      clearCart,
      addCart,
      delCart,
      singleCheck,
      allCheck,
      updateNewList,
    };
  },
  {
    persist: true,
  }
);
